import { Component } from "cc";
import { _decorator } from "cc";
import NDB from "./common/NDBTS";
import { SceneAsset } from "cc";
import { JsonAsset } from "cc";
import { sys } from "cc";
import { eventManager } from "./common/eventManager";
import { director } from "cc";
import { SpriteFrame } from "cc";
import { Sprite } from "cc";
import { Label } from "cc";
import { ProgressBar } from "cc";
import nsnoSleep from "./common/nosleep";
import NetworkManager from "./common/NetworkManager";
import { GameConfig } from "./GameConfig";
import { resourceManager } from "./common/ResourceManager";
import { getUrlParameterValue } from "./common/util";
import { Node } from "cc";
import { CCString } from "cc";
import { Prefab } from "cc";

const { ccclass, property } = _decorator;

@ccclass
export default class FullScreenLoadScene extends Component {

    /**是否切换到匹配场景 */
    public static isGotoMatchScene = false;

    @property(JsonAsset)
    allToyJson: JsonAsset = null;

    @property([SpriteFrame])
    icons: SpriteFrame[] = [];

    @property(Sprite)
    loadIcon: Sprite = null;

    @property(Label)
    proLabel: Label = null;
    @property(ProgressBar)
    progressBar: ProgressBar = null;

    @property(CCString)
    LoadSceneName: string = '';

    private isChange: boolean = false;
    private progressLabelIsShow: boolean = false;

    private prefabsLoadOver: boolean = false;
    private sceneLoadOver: boolean = false;
    private resZipOver: boolean = false;

    private hasLoadGameScene: boolean = false;

    onLoad() {
        console.log("---load ratio ");
        console.log(GameConfig.gameName + " onload");
        NetworkManager.Init();
        this._initIcon();

        // this._loadLang();
        this.LoadSceneName = GameConfig.gameName + "_GameScene";

        const toysValue = Object.values(this.allToyJson.json);
        console.time("load models...");

        console.log("version is ", "v1.0");

        // resourceManager.loadBundleDir(GameConfig.gameName, "prefabs", Prefab, null, (err, res) => {
        //     if (err) return;
        //     console.timeEnd("load models...");
        // });
        for (let i = 0; i < toysValue.length; i++) {
            const toy = toysValue[i];
            resourceManager.loadAssetInBundle(`prefabs/${toy}`, Prefab, GameConfig.gameName).then(() => {
                // 标记该资源加载完毕
                // eliminateConsts.toysLoadInfo[toy] = true;
                if (i == toysValue.length - 1) {
                    console.timeEnd("load models...");
                    this.prefabsLoadOver = true;
                }
            });
        }

        // this.joinGame().then(() => {
        //     if (eliminateGameManager.curLevel == 1 || eliminateGameManager.curLevel == 2) {
        //         // 预加载第一关和第二关的物品 针对新用户 进入游戏按帧加载其他的物品
        //         const toys = eliminateConsts.firstLevel_toys;
        //         for (let i = 0; i < toys.length; i++) {
        //             let toy = toys[i];
        //             resourceManager.loadAssetInBundle(`prefabs/${toy}`, Prefab, GameConfig.gameName).then(() => {
        //                 // 标记该资源加载完毕
        //                 eliminateConsts.toysLoadInfo[toy] = true;
        //                 if (i == toys.length - 1) {
        //                     this.prefabsLoadOver = true;
        //                 }
        //             });
        //         }
        //     } else {
        //         const toysValue = Object.values(this.allToyJson.json).values;
        //         for (let i = 0; i < toysValue.length; i++) {
        //             const toy = toysValue[i];
        //             resourceManager.loadAssetInBundle(`prefabs/${toy}`, Prefab, GameConfig.gameName).then(() => {
        //                 // 标记该资源加载完毕
        //                 eliminateConsts.toysLoadInfo[toy] = true;
        //                 if (i == toysValue.length - 1) {
        //                     this.prefabsLoadOver = true;
        //                 }
        //             });
        //         }
        //     }
        // }).catch(() => {
        //     this.prefabsLoadOver = true;
        // })
        resourceManager.loadSceneInBundle(`scene/${GameConfig.gameName}_GameScene`, GameConfig.gameName, () => {
        }).then((res: SceneAsset) => {
            if (res) {
                console.log("场景加载完毕");
                this.sceneLoadOver = true;
            }
        });
    }

    // public async joinGame() {
    //     return new Promise((resolve, reject) => {
    //         NetworkManager.httpResult("post", NetworkMessage.ELIMINATE3D_JOIN, {}, (res: { data: JoinResponse }) => {
    //             console.log("join res is ", res);
    //             eliminateGameManager.curLevel = res.data.current_max_level;
    //             eliminateGameManager.curPlayLevel = res.data.current_max_level;
    //             eliminateGameManager.game.score = res.data.current_score;
    //             resolve(null);
    //         });
    //     })
    // }

    onEnable() {
        this.node.on(Node.EventType.TOUCH_END, this.tapNode, this);
    }

    onDisable() {
        this.node.off(Node.EventType.TOUCH_END, this.tapNode, this);
    }

    tapNode() {
        const ns = new nsnoSleep();
        ns.enable();
    }

    // _loadLang() {
    //     // const uilang = MessageManager.getUrlParameterValue("ui_lang");
    //     // console.log("uilang is ", uilang);
    //     let lang = getUrlParameterValue('ui_lang') || 'en';
    //     console.log("lang is ", lang);
    //     resourceManager.loadBundleDir(GameConfig.gameName, 'lang', JsonAsset, null, (err, res: JsonAsset[]) => {
    //         if (err) {
    //             console.log("加载多语言失败");
    //             return;
    //         }
    //         console.log("res is ", res);
    //         commonLang.curCommonLang = commonLang.commonLang[lang];

    //         res.forEach(item => {
    //             if (item.name == 'en') {
    //                 langManager.defaultLang = item.json;
    //             }
    //             if (item.name == lang) {
    //                 console.log("name is ", item.name);
    //                 langManager.curLang = item.json;
    //             }
    //         });
    //         console.log("curLang is ", langManager.curLang);
    //     })
    // }

    _initIcon() {
        for (let i = 0, len = this.icons.length; i < len; i++) {
            const iconName = this.icons[i].name;
            // @ts-ignore
            if (GameConfig.gameName == "crazyLions" || GameConfig.gameName == "slots") {
                if (GameConfig.gameName == "crazyLions") {
                    this.loadIcon.spriteFrame = this.icons[2];
                } else {
                    this.loadIcon.spriteFrame = this.icons[0];
                }
                continue;
            }
            if (iconName == GameConfig.gameName) {
                this.loadIcon.spriteFrame = this.icons[i];
            }
        }
    }

    async start() {
        const source = window.location.href;
        const isStaging = source.match('staging');
        // if (isStaging && this.versionLabel) {
        //     this.versionLabel = true;
        // }
        this.eventDispatchFunc();

        const vcode: number = Number(getUrlParameterValue('vcode'));
        let need_gzip: string = getUrlParameterValue('need_gzip');
        //版本号/安卓/need_gzip为true  || isStaging测试环境;
        if (sys.isBrowser && need_gzip === 'true') {
            this.getZip();
        } else {
            this.resZipOver = true;
            this.changeScene(false);
        }
    }

    async getZip() {

        const source3D = "http://a.fslk.co/games/zips/prod/cocos-3d.zip";
        const resources = {
            "match3d": "http://a.fslk.co/games/zips/prod/match3d02.zip"
        }
        // console.log("source 3d is ", source3D);
        // let cocosSourceUrl = source3D;
        let resSourceUrl = resources[GameConfig.gameName];
        switch (GameConfig.gameName) {
            // @ts-ignore
            case "match3d":
                resSourceUrl = resources[GameConfig.gameName];
                break;
        }

        try {
            // let dataCocos = await NDB.isGameSourceExisted(cocosSourceUrl);
            let gameSource = await NDB.isGameSourceExisted(resSourceUrl);

            console.log("gameSource is ", gameSource);
            if (gameSource['isHave']) {
                this.changeScene(false);
            }
        } catch (e) {
            this.changeScene(false);
        }

    }

    //消息监听；
    eventDispatchFunc() {
        //当前下载进度;
        eventManager.on('onDownloadProgress', this.onDownloadProgress.bind(this), this.node);
        //下载完成；
        eventManager.on('onDownloadFinish', this.onDownloadFinish.bind(this), this.node);
        //下载失败;
        eventManager.on('onDownloadFailed', this.onDownloadFailed.bind(this), this.node);
        //socket消息；
        eventManager.on('emit_message', this.messageFunc.bind(this), this.node);
    }

    //socket消息；
    messageFunc(mData) {
        const method: string = mData.data.method;
        if (method === 'response_ws_status') {
            const online: boolean = mData.data.data.online;
            if (online) {
                this.isChange = false;
                this.changeScene(false);
            }
        }
    }

    //当前下载进度;
    onDownloadProgress(p: number) {
        if (this.hasLoadGameScene) return;
        this.showProgressLabelIsShow();
        let pro = Math.ceil(Number(p['progress']) * 0.9);
        if (+this.translate(this.proLabel.string) > pro) return;

        this.proLabel.string = pro.toString() + '%';
        this.progressBar.progress = pro / 100;
    }

    //下载完成；
    onDownloadFinish() {
        if (this.hasLoadGameScene) return;
        this.proLabel.string = '90%';
        this.changeScene(true);
    }

    //下载失败；
    onDownloadFailed() {
        if (this.hasLoadGameScene) return;
        this.showProgressLabelIsShow();
        this.changeScene(false);
    }

    translate = (s: string) => {
        const sarr = s.split('');
        return sarr.slice(0, sarr.length - 1).join('');
    }

    //切换场景;
    changeScene(flag: boolean) {

        if (this.isChange) {
            return;
        }
        this.showProgressLabelIsShow();
        this.isChange = true;
        let t = this;
        resourceManager.loadSceneInBundle(`scene/${GameConfig.gameName}_GameScene`, GameConfig.gameName, () => {
        }, (completedCount, totalCount) => {
            let comple = Math.floor(completedCount / totalCount * 100);
            console.log("comple is ", comple, " proLabel is ", t.proLabel.string);
            if (flag) {
                let pro = 90 + Math.ceil(comple / 10);
                if (+this.translate(t.proLabel.string) > pro) {
                    console.log("pro is ", pro, " label is ", t.proLabel.string);
                    return;
                };

                t.proLabel.string = pro.toString() + '%';
                t.progressBar.progress = pro / 100;
            } else {
                if (+this.translate(t.proLabel.string) > comple) {
                    console.log("pro is ", comple, " label is ", t.proLabel.string);
                    return;
                };

                t.progressBar.progress = comple / 100;
                t.proLabel.string = comple.toString() + '%';
            }
            if (comple == 100) {
                if (FullScreenLoadScene.isGotoMatchScene) {
                    return;
                }
                console.log("资源压缩包加载完毕");
                this.resZipOver = true;
            }
        }).then((res: SceneAsset) => {
            console.log('scene res is ', res);
            this.sceneLoadOver = true;
        });
    }

    showProgressLabelIsShow() {
        if (this.progressLabelIsShow) {
            return;
        }
        this.progressLabelIsShow = true;
        this.proLabel.node.active = true;
    }

    protected update(dt: number): void {
        if (this.resZipOver && this.sceneLoadOver && this.prefabsLoadOver && !this.hasLoadGameScene) {
            director.loadScene(this.LoadSceneName);
            this.hasLoadGameScene = true;
        }
    }

}

